﻿namespace DotNetUtility.ExtensionMethods
{
    using System;

    /// <summary>
    /// Different extensions method for enum.
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        ///  An extension method for string to parse enum.
        /// </summary>
        /// <typeparam name="TEnum">The type of enum.</typeparam>
        /// <param name="dataToMatch">The string data on which this extension will apply.</param>
        /// <param name="ignorecase">whether the string case will be considered or not.</param>
        /// <returns>Matched enum value.</returns>
        /// <example>
        ///     <code>
        ///         enum YesNo
        ///         {
        ///             Yes =0,
        ///             No
        ///         }
        ///         YesNo result = "Yes".ParseStringToEnum<YesNo>();
        ///     </code>
        /// </example>
        /// Contributed by Mohammad Rahman
        public static TEnum ParseStringToEnum<TEnum>
            (this string dataToMatch, bool ignorecase = default(bool))
            where TEnum : struct
        {
            return dataToMatch.IsItemInEnum<TEnum>() ? (TEnum)Enum.Parse(typeof(TEnum), dataToMatch, ignorecase) : default(TEnum);
        }

        /// <summary>
        ///  To check whether there are an matched value in the enum.
        /// </summary>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <param name="dataToCheck">The string data to check.</param>
        /// <returns>Lambda block which will contain the boolean result whether the data is defined in the enum or not.</returns>
        /// <example>
        ///     <code>
        ///         string itemToCheck ="Yes";
        ///         bool result = itemToCheck.IsItemInEnum<YesNo>()();
        ///     </code>
        /// </example>
        /// Contributed by Mohammad Rahman
        public static bool IsItemInEnum<TEnum>(this string dataToCheck)
            where TEnum : struct
        {
            return !string.IsNullOrEmpty(dataToCheck) && Enum.IsDefined(typeof(TEnum), dataToCheck);
        }
    }
}
